package com.example.testing;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;

public class Loading extends Activity {
    String URL = "http://smoothalicious.nl/webservice/testConnection.php",
    		result = "result",
    		details = "details";
    int waitSeconds = 3;
    Boolean pressedOnce;
    
    List<NameValuePair> params;
    ProgressDialog progressDialog;
    Intent intent;
    JSONParser jsonParser;
    JSONObject jsonObject;
    AsyncTask<String, String, String> testConnection;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
      	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
      	setContentView(R.layout.loading);
      	
      	pressedOnce = false;
      	
      	testConnection = new testConnection().execute();
	}
	
	class testConnection extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

		@Override
		protected String doInBackground(String... args) {
			try {
				params = new ArrayList<NameValuePair>();
				
				jsonParser = new JSONParser();
                jsonObject = jsonParser.makeHttpRequest(URL, "POST", params);
                
            	Thread.sleep(waitSeconds * 1000);
                
                if(jsonObject.getInt(result) == 1) {
            		intent = new Intent(Loading.this, LoginUser.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Loading.this.startActivity(intent);
                    
                    finish();
                } else {
                	return jsonObject.getString(details);
                }                
            } catch (Exception exception) {
                return exception.toString();
            }
			
			return null;
		}
		
        protected void onPostExecute(String details) {
        	if(details != null) {
        		Toast.makeText(Loading.this, details, Toast.LENGTH_LONG).show();        		
        	}
        }
	}
	
	@Override
	protected void onResume() {
	    super.onResume();

	    pressedOnce = false;
	}

	@Override
	public void onBackPressed() {
	    if (pressedOnce) {
	        super.onBackPressed();
	        
	        finish();
	        testConnection.cancel(true);
	    } else {
	    	pressedOnce = true;
		    Toast.makeText(this, "Druk nog eens op terug om de app af te sluiten", Toast.LENGTH_SHORT).show();	    	
	    }
	}
}
